<template>
  <div class="warehouse-management">
    <!-- 操作栏：新增按钮 + 搜索 -->
    <div class="operation-bar">
      <div class="left-actions">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增仓库</el-button>
      </div>
      <div class="search-group">
        <el-input
          v-model="searchForm.warehouseName"
          placeholder="请输入仓库名称"
          clearable
          style="width: 200px;"
          @keyup.enter.native="handleSearch"
        />
        <el-button type="primary" icon="el-icon-search" @click="handleSearch"></el-button>
        <el-button type="primary" icon="el-icon-s-operation" @click="handleFilter"></el-button>
      </div>
    </div>


    <!-- 仓库表格 -->
    <el-card class="table-card">
      <el-table 
        :data="tableData" 
        v-loading="loading"
        border 
        stripe
        style="width: 100%;"
      >
        <el-table-column label="序号" type="index" width="40" />
        <el-table-column prop="warehouseName" label="仓库名称" min-width="100" show-overflow-tooltip />
        <el-table-column label="仓库归属" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ getCommunityName(scope.row.communityId) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.warehouseStatus === 1 ? 'success' : 'danger'" size="small">
              {{ scope.row.warehouseStatus === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contactName" label="联系人" min-width="100" show-overflow-tooltip />
        <el-table-column prop="contactPhone" label="联系电话" min-width="120" show-overflow-tooltip />
        <el-table-column prop="email" label="邮箱" min-width="150" show-overflow-tooltip />
        <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">修改</el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.warehouseStatus === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button type="text" size="small" style="color: #f56c6c;" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>


      <!-- 分页 -->
      <div class="pagination-wrap">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pagination.pageSize"
          layout="prev, pager, next, sizes, jumper"
          :total="pagination.total"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="warehouseForm"
        :model="warehouseForm"
        :rules="warehouseRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="仓库名称" prop="warehouseName">
              <el-input v-model="warehouseForm.warehouseName" placeholder="请输入仓库名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="仓库归属" prop="communityId">
              <el-select v-model="warehouseForm.communityId" placeholder="请选择小区" style="width: 100%;">
                <el-option
                  v-for="community in communityList"
                  :key="community.communityId"
                  :label="community.communityName"
                  :value="community.communityId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactName">
              <el-input v-model="warehouseForm.contactName" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="warehouseForm.contactPhone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="warehouseForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="warehouseForm.address" type="textarea" :rows="3" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="warehouseForm.remarks" type="textarea" :rows="2" placeholder="请输入备注信息" />
        </el-form-item>
        <el-form-item label="状态" prop="warehouseStatus">
          <el-radio-group v-model="warehouseForm.warehouseStatus">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { warehouseApi } from '@/api/warehouse'

export default {
  name: 'WarehouseManagement',
  data() {
    return {
      loading: false,
      submitLoading: false,
      dialogVisible: false,
      dialogTitle: '新增仓库',
      isEdit: false,
      
      // 搜索表单
      searchForm: {
        warehouseName: '',
        status: ''
      },
      
      // 分页信息
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      
      // 小区列表
      communityList: [],
      
      // 表格数据
      tableData: [
        {
          warehouseId: '1',
          warehouseName: 'XXXX仓库',
          communityId: 'comm001',
          warehouseStatus: 1,
          contactName: '李晓琪',
          contactPhone: '188988888888',
          email: 'ppp@zuy.com',
          address: '成都市武侯区XXXX路XXX号',
          remarks: '备注信息'
        },
        {
          warehouseId: '2',
          warehouseName: 'XXXX仓库',
          communityId: 'comm002',
          warehouseStatus: 0,
          contactName: '李晓琪',
          contactPhone: '188988888888',
          email: 'ppp@zuy.com',
          address: '成都市武侯区XXXX路XXX号',
          remarks: '备注信息'
        },
        {
          warehouseId: '3',
          warehouseName: 'XXXX仓库',
          communityId: 'comm001',
          warehouseStatus: 1,
          contactName: '李晓琪',
          contactPhone: '188988888888',
          email: 'ppp@zuy.com',
          address: '成都市武侯区XXXX路XXX号',
          remarks: '备注信息'
        },
        {
          warehouseId: '4',
          warehouseName: 'XXXX仓库',
          communityId: 'comm003',
          warehouseStatus: 0,
          contactName: '李晓琪',
          contactPhone: '188988888888',
          email: 'ppp@zuy.com',
          address: '成都市武侯区XXXX路XXX号',
          remarks: '备注信息'
        },
        {
          warehouseId: '5',
          warehouseName: 'XXXX仓库',
          communityId: 'comm002',
          warehouseStatus: 1,
          contactName: '李晓琪',
          contactPhone: '188988888888',
          email: 'ppp@zuy.com',
          address: '成都市武侯区XXXX路XXX号',
          remarks: '备注信息'
        },
        {
          warehouseId: '6',
          warehouseName: 'XXXX仓库',
          communityId: 'comm001',
          warehouseStatus: 0,
          contactName: '李晓琪',
          contactPhone: '188988888888',
          email: 'ppp@zuy.com',
          address: '成都市武侯区XXXX路XXX号',
          remarks: '备注信息'
        },
        {
          warehouseId: '7',
          warehouseName: 'XXXX仓库',
          communityId: 'comm003',
          warehouseStatus: 1,
          contactName: '李晓琪',
          contactPhone: '188988888888',
          email: 'ppp@zuy.com',
          address: '成都市武侯区XXXX路XXX号',
          remarks: '备注信息'
        },
        {
          warehouseId: '8',
          warehouseName: 'XXXX仓库',
          communityId: 'comm002',
          warehouseStatus: 0,
          contactName: '李晓琪',
          contactPhone: '188988888888',
          email: 'ppp@zuy.com',
          address: '成都市武侯区XXXX路XXX号',
          remarks: '备注信息'
        },
        {
          warehouseId: '9',
          warehouseName: 'XXXX仓库',
          communityId: 'comm001',
          warehouseStatus: 1,
          contactName: '李晓琪',
          contactPhone: '188988888888',
          email: 'ppp@zuy.com',
          address: '成都市武侯区XXXX路XXX号',
          remarks: '备注信息'
        },
        {
          warehouseId: '10',
          warehouseName: 'XXXX仓库',
          communityId: 'comm003',
          warehouseStatus: 0,
          contactName: '李晓琪',
          contactPhone: '188988888888',
          email: 'ppp@zuy.com',
          address: '成都市武侯区XXXX路XXX号',
          remarks: '备注信息'
        }
      ],
      
      // 表单数据
      warehouseForm: {
        warehouseName: '',
        communityId: '',
        contactName: '',
        contactPhone: '',
        email: '',
        address: '',
        remarks: '',
        warehouseStatus: 1
      },
      
      // 表单验证规则
      warehouseRules: {
        warehouseName: [
          { required: true, message: '请输入仓库名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        communityId: [
          { required: true, message: '请输入仓库归属', trigger: 'blur' }
        ],
        contactName: [
          { required: true, message: '请输入联系人', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入地址', trigger: 'blur' }
        ],
        warehouseStatus: [
          { required: true, message: '请选择仓库状态', trigger: 'change' }
        ]
      }
    }
  },
  
  
  mounted() {
    this.loadData();
    this.loadCommunities();
  },
  
  methods: {
    // 加载数据
    async loadData() {
      this.loading = true;
      try {
        const params = {
          warehouseName: this.searchForm.warehouseName,
          warehouseStatus: this.searchForm.status,
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        };
        
        const response = await warehouseApi.getWarehousePage(params);
        if (response.code === 200) {
          this.tableData = response.data.records || response.data.list || [];
          this.pagination.total = response.data.total || 0;
        } else {
          this.$message.error(response.message || '获取数据失败');
        }
      } catch (error) {
        console.error('加载数据失败:', error);
        this.$message.error('加载数据失败，请稍后重试');
        // 使用模拟数据作为降级方案
        this.pagination.total = this.tableData.length;
      } finally {
        this.loading = false;
      }
    },
    
    // 加载小区数据
    async loadCommunities() {
      try {
        const response = await warehouseApi.getAllCommunities();
        if (response.code === 200) {
          this.communityList = response.data || [];
        } else {
          this.$message.error(response.message || '获取小区列表失败');
        }
      } catch (error) {
        console.error('加载小区数据失败:', error);
        this.$message.error('加载小区数据失败，请稍后重试');
        // 使用模拟数据作为降级方案
        this.communityList = [
          { communityId: 'comm001', communityName: '中山国际' },
          { communityId: 'comm002', communityName: '阳光花园' },
          { communityId: 'comm003', communityName: '绿城小区' }
        ];
      }
    },
    
    // 根据小区ID获取小区名称
    getCommunityName(communityId) {
      if (!communityId) return '-';
      const community = this.communityList.find(item => item.communityId === communityId);
      return community ? community.communityName : '-';
    },
    
    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1;
      this.loadData();
    },
    
    // 重置搜索
    handleReset() {
      this.searchForm = {
        warehouseName: '',
        status: ''
      };
      this.handleSearch();
    },
    
    // 筛选
    handleFilter() {
      // 这里可以添加筛选逻辑，比如显示筛选面板
      this.$message.info('筛选功能');
    },
    
    // 新增
    handleAdd() {
      this.dialogTitle = '新增仓库';
      this.isEdit = false;
      this.warehouseForm = {
        warehouseName: '',
        communityId: '',
        contactName: '',
        contactPhone: '',
        email: '',
        address: '',
        remarks: '',
        warehouseStatus: 1
      };
      this.dialogVisible = true;
    },
    
    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑仓库';
      this.isEdit = true;
      this.warehouseForm = {
        warehouseId: row.warehouseId,
        warehouseName: row.warehouseName,
        communityId: row.communityId,
        contactName: row.contactName,
        contactPhone: row.contactPhone,
        email: row.email,
        address: row.address,
        remarks: row.remarks || '',
        warehouseStatus: row.warehouseStatus
      };
      this.dialogVisible = true;
    },
    
    // 查看
    handleView(row) {
      this.$alert(`
        <div style="text-align: left;">
          <p><strong>仓库名称：</strong>${row.warehouseName}</p>
          <p><strong>仓库归属：</strong>${row.warehouseBelong}</p>
          <p><strong>状态：</strong>${row.status === 1 ? '启用' : '禁用'}</p>
          <p><strong>联系人：</strong>${row.contact}</p>
          <p><strong>联系电话：</strong>${row.phone}</p>
          <p><strong>邮箱：</strong>${row.email}</p>
          <p><strong>地址：</strong>${row.address}</p>
          <p><strong>创建时间：</strong>${row.createTime}</p>
        </div>
      `, '仓库详情', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定'
      });
    },
    
    // 删除
    async handleDelete(row) {
      this.$confirm('确定要删除该仓库吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const response = await warehouseApi.deleteWarehouse(row.warehouseId);
          if (response.code === 200) {
            this.$message.success('删除成功');
            this.loadData();
          } else {
            this.$message.error(response.message || '删除失败');
          }
        } catch (error) {
          console.error('删除失败:', error);
          this.$message.error('删除失败，请稍后重试');
        }
      });
    },
    
    // 切换状态
    async handleToggleStatus(row) {
      const action = row.warehouseStatus === 1 ? '禁用' : '启用';
      this.$confirm(`确定要${action}该仓库吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const newStatus = row.warehouseStatus === 1 ? 0 : 1;
          const response = await warehouseApi.updateWarehouseStatus(row.warehouseId, newStatus);
          if (response.code === 200) {
            row.warehouseStatus = newStatus;
            this.$message.success(`${action}成功`);
          } else {
            this.$message.error(response.message || `${action}失败`);
          }
        } catch (error) {
          console.error(`${action}失败:`, error);
          this.$message.error(`${action}失败，请稍后重试`);
        }
      });
    },
    
    
    
    // 提交表单
    async handleSubmit() {
      this.$refs.warehouseForm.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true;
          try {
            let response;
            if (this.isEdit) {
              // 编辑
              response = await warehouseApi.updateWarehouse(this.warehouseForm);
            } else {
              // 新增
              response = await warehouseApi.addWarehouse(this.warehouseForm);
            }
            
            if (response.code === 200) {
              this.$message.success(this.isEdit ? '编辑成功' : '新增成功');
              this.dialogVisible = false;
              this.loadData();
            } else {
              this.$message.error(response.message || (this.isEdit ? '编辑失败' : '新增失败'));
            }
          } catch (error) {
            console.error('提交失败:', error);
            this.$message.error('操作失败，请稍后重试');
          } finally {
            this.submitLoading = false;
          }
        }
      });
    },
    
    // 关闭对话框
    handleDialogClose() {
      this.$refs.warehouseForm.resetFields();
    },
    
    // 分页
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.loadData();
    },
    
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.loadData();
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '-';
      return dateStr;
    }
  }
}
</script>

<style scoped>
.warehouse-management {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}


/* 操作栏 */
.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.left-actions {
  display: flex;
  gap: 12px;
}

.search-group {
  display: flex;
  align-items: center;
  gap: 8px;
}


/* 表格卡片 */
.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}


/* 分页 */
.pagination-wrap {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 16px 0;
}

/* 对话框 */
.dialog-footer {
  text-align: right;
}

/* 表格样式优化 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

.el-table td {
  padding: 12px 0;
}

/* 按钮样式 */
.el-button {
  border-radius: 4px;
  font-weight: 500;
}

.el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.el-button--primary:hover {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

.el-button--success {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  border: none;
}

.el-button--warning {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
  border: none;
}

/* 标签样式 */
.el-tag {
  border-radius: 12px;
  font-weight: 500;
}

/* 输入框样式 */
.el-input__inner {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: border-color 0.3s ease;
}

.el-input__inner:focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

/* 选择器样式 */
.el-select .el-input__inner {
  border-radius: 4px;
}

/* 卡片阴影效果 */
.el-card {
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .warehouse-management {
    padding: 10px;
  }
  
  .operation-bar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .left-actions {
    justify-content: center;
  }
  
  .search-group {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .stat-content {
    padding: 16px;
  }
  
  .stat-icon {
    width: 50px;
    height: 50px;
    font-size: 20px;
  }
  
  .stat-number {
    font-size: 24px;
  }
}

/* 加载动画 */
.el-loading-mask {
  border-radius: 8px;
}

/* 表格行悬停效果 */
.el-table--striped .el-table__body tr:hover > td {
  background-color: #f5f7fa;
}

/* 操作按钮间距 */
.el-table .el-button + .el-button {
  margin-left: 8px;
}

/* 状态标签动画 */
.el-tag {
  transition: all 0.3s ease;
}

/* 分页器样式 */
.el-pagination {
  text-align: right;
}

.el-pagination .el-pager li {
  border-radius: 4px;
  margin: 0 2px;
}

.el-pagination .el-pager li.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
}
</style>